package com.ruoyi.safe.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quality.domain.TQualityFileItem;
import com.ruoyi.quality.service.ITQualityFileItemService;
import com.ruoyi.safe.constant.DictTypeConstants;
import com.ruoyi.safe.domain.BizProjectCheckRecord;
import com.ruoyi.safe.domain.BizRectifyReview;
import com.ruoyi.safe.domain.BizSafeAttach;
import com.ruoyi.safe.domain.BizSafeFine;
import com.ruoyi.safe.domain.dto.BizRectifyReviewDTO;
import com.ruoyi.safe.mapper.BizProjectCheckRecordMapper;
import com.ruoyi.safe.mapper.BizRectifyReviewMapper;
import com.ruoyi.safe.mapper.BizSafeAttachMapper;
import com.ruoyi.safe.mapper.BizSafeFineMapper;
import com.ruoyi.safe.service.IBizRectifyReviewService;
import com.ruoyi.safe.service.IBizSafeAttachService;
import com.ruoyi.safe.service.IBizSafeBillnoService;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 复查--整改Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-22
 */
@Service
@RequiredArgsConstructor
public class BizRectifyReviewServiceImpl implements IBizRectifyReviewService {

    private final BizRectifyReviewMapper bizRectifyReviewMapper;

    private final IBizSafeAttachService bizSafeAttachService;


    //    private final BizProjectCheckRecordMapper projectCheckRecordMapper;

    @Autowired
    private final ITQualityFileItemService tQualityFileItemService;

    private final RedisCache redisCache;

    private final IBizSafeBillnoService bizSafeBillnoService;

    private final SysDeptMapper sysDeptMapper;

    private final BizSafeFineMapper bizSafeFineMapper;

    private final SysUserMapper sysUserMapper;

    @Autowired
    private BizSafeAttachMapper bizSafeAttachMapper;

    /**
     * 查询复查--整改
     *
     * @param id 复查--整改主键
     * @return 复查--整改
     */
    @Override
    public BizRectifyReview selectBizRectifyReviewById(Long id) {
        return bizRectifyReviewMapper.selectBizRectifyReviewById(id);
    }

    /**
     * 查询复查--整改列表
     *
     * @param bizRectifyReview 复查--整改
     * @return 复查--整改
     */
    @Override
    public List<BizRectifyReview> selectBizRectifyReviewList(BizRectifyReview bizRectifyReview) {
        return bizRectifyReviewMapper.selectBizRectifyReviewList(bizRectifyReview);
    }

    /**
     * 查询复查--整改列表，同时查询整改和复查
     *
     * @param bizRectifyReview 复查--整改
     * @return 复查--整改集合
     */
    @Override
    public List<BizRectifyReview> selectBizRectifyReviewList2(BizRectifyReview bizRectifyReview) {
        return bizRectifyReviewMapper.selectBizRectifyReviewList2(bizRectifyReview);
    }

    /**
     * 新增整改数据
     *
     * @param bizRectifyReview 复查--整改
     * @return 结果
     */
    @Override
    public int insertBizRectifyReview(BizRectifyReview bizRectifyReview) {
        bizRectifyReview.setCreateBy(SecurityUtils.getUsername());
        bizRectifyReview.setCreateTime(DateUtils.getNowDate());
        return bizRectifyReviewMapper.insertBizRectifyReview(bizRectifyReview);
    }

    /**
     * 修改复查--整改
     *
     * @param bizRectifyReview 复查--整改
     * @return 结果
     */
    @Override
    public int updateBizRectifyReview(BizRectifyReview bizRectifyReview) {
        bizRectifyReview.setUpdateBy(SecurityUtils.getUsername());
        bizRectifyReview.setUpdateTime(DateUtils.getNowDate());
        return bizRectifyReviewMapper.updateBizRectifyReview(bizRectifyReview);
    }

    /**
     * 批量删除复查--整改
     *
     * @param ids 需要删除的复查--整改主键
     * @return 结果
     */
    @Override
    public int deleteBizRectifyReviewByIds(Long[] ids) {
        return bizRectifyReviewMapper.deleteBizRectifyReviewByIds(ids);
    }

    /**
     * 删除复查--整改信息
     *
     * @param id 复查--整改主键
     * @return 结果
     */
    @Override
    public int deleteBizRectifyReviewById(Long id) {
        return bizRectifyReviewMapper.deleteBizRectifyReviewById(id);
    }

    @Override
    public List<BizRectifyReview> selectListByOperatorType(Long recordId, String operatorType) {
        return bizRectifyReviewMapper.selectListByOperatorType(recordId, operatorType);
    }

    /**
     * 查询操作记录数据
     *
     * @param recordId
     * @return
     */
    @Override
    public List<BizRectifyReview> selectOperateList(Long recordId) {
        List<BizRectifyReview> bizRectifyReviews = bizRectifyReviewMapper.selectOperateList(recordId);
        Set<Long> collect = bizRectifyReviews.stream().map(r -> r.getId()).collect(Collectors.toSet());
        if (collect.size() > 0) {
            List<BizSafeAttach> bizSafeAttaches = bizSafeAttachMapper.selectBizSafeAttachByBizIds(collect);
            for (int i = 0; i < bizRectifyReviews.size(); i++) {
                BizRectifyReview bizRectifyReview = bizRectifyReviews.get(i);
                int reviewsIndex = i;
                List<BizSafeAttach> attachList = bizSafeAttaches.stream().filter(a -> bizRectifyReviews.get(reviewsIndex).getId().equals(a.getBizId())).collect(Collectors.toList());
//                bizRectifyReview.setAttachList(attachList);

                if(bizRectifyReview.getOperatorStatus() != null){
                    bizRectifyReview.setOperatorStatusName(DictUtils.getDictLabel(DictTypeConstants.OPERATOR_STATUS,bizRectifyReview.getOperatorStatus()));
                }
            }
        }

        return bizRectifyReviews;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addRectifyReview(BizRectifyReviewDTO bizRectifyReviewDTO) {
        // 复查整改数据从dto复制到实体类
        BizRectifyReview rectifyReview = new BizRectifyReview();
        BeanUtil.copyProperties(bizRectifyReviewDTO, rectifyReview);
        if (StrUtil.isNotEmpty(SecurityUtils.getUsername())) {
            bizRectifyReviewDTO.setUserName(SecurityUtils.getUsername());
        }
        // 主键id，使用雪花算法获取
        rectifyReview.setId(IdUtil.getSnowflakeNextId());

        // 查询项目自检-检查记录
        TQualityFileItem tQualityFileItem = tQualityFileItemService.selectTQualityFileItemById(bizRectifyReviewDTO.getRecordId());

        String[] subpackageUnitIds = bizRectifyReviewDTO.getSubpackageUnitIds().split(",");
        SysUser sysUser = sysUserMapper.selectUserByUserName(bizRectifyReviewDTO.getUserName());
        SysDept sysDept = sysDeptMapper.selectDeptById(sysUser.getDeptId());
        if (bizRectifyReviewDTO.getSubpackageUnitIds() != null && !bizRectifyReviewDTO.getSubpackageUnitIds().isEmpty()) {

            for (String subpackageUnit : subpackageUnitIds)
            {
                bizSafeFineMapper.insertBizSafeFine(BizSafeFine.builder()
                        .safeNumber(bizSafeBillnoService.getSafeNumber(1L))
                        .fineUnit(sysDept.getDeptName())
                        .fineUser(subpackageUnit)
                        .fineExplain(bizRectifyReviewDTO.getFineExplain())
                        .fineSource("1")
                        .fineMoney(bizRectifyReviewDTO.getFineMoney())
                        .projectId(bizRectifyReviewDTO.getProjectId())
                        .recordId(tQualityFileItem.getId())
                        .fineButton("1")
                        .createBy(bizRectifyReviewDTO.getUserName())
                        .createTime(new Date())
                        .build());
            }
        }
        else {
            bizSafeFineMapper.insertBizSafeFine(BizSafeFine.builder()
                    .safeNumber(bizSafeBillnoService.getSafeNumber(1L))
                    .fineUnit(sysDept.getDeptName())
                    .fineUser("")
                    .fineExplain(bizRectifyReviewDTO.getFineExplain())
                    .fineSource("1")
                    .fineMoney(bizRectifyReviewDTO.getFineMoney())
                    .projectId(bizRectifyReviewDTO.getProjectId())
                    .recordId(tQualityFileItem.getId())
                    .fineButton("2")
                    .createBy(bizRectifyReviewDTO.getUserName())
                    .createTime(new Date())
                    .build());
        }

        //去掉重复和空字符串的分包单位
        Set<String> subpackageUnit = new HashSet<>();

        if (ObjectUtil.isNotEmpty(tQualityFileItem.getSubpackageUnit())) {
            subpackageUnit.addAll(Arrays.stream(tQualityFileItem.getSubpackageUnit().split(","))
                    .filter(StrUtil::isNotEmpty).collect(Collectors.toSet()));
        }

        if (ObjectUtil.isNotEmpty(bizRectifyReviewDTO.getSubpackageUnitIds())) {
            subpackageUnit.addAll(Arrays.stream(bizRectifyReviewDTO.getSubpackageUnitIds().split(","))
                    .filter(StrUtil::isNotEmpty).collect(Collectors.toSet()));
        }

        tQualityFileItem.setSubpackageUnit(StrUtil.join(",", subpackageUnit));

        if (rectifyReview.getOperatorStatus().equals("1"))
        {
            tQualityFileItem.setCheckTime(new Date());
            tQualityFileItem.setDataStatus("1");
        }
        else if (rectifyReview.getOperatorStatus().equals("2"))
        {
            tQualityFileItem.setReviewTime(new Date());
            tQualityFileItem.setDataStatus("0");
        }
        else if (rectifyReview.getOperatorStatus().equals("3"))
        {
            tQualityFileItem.setReviewTime(new Date());
            tQualityFileItem.setDataStatus("2");
        }

        rectifyReview.setOperatorType("2");
        if (rectifyReview.getOperatorStatus().equals("2"))
        {
            tQualityFileItem.setReviewTime(new Date());
            tQualityFileItem.setDataStatus("0");
        }
        else if (rectifyReview.getOperatorStatus().equals("3"))
        {
            tQualityFileItem.setReviewTime(new Date());
            tQualityFileItem.setDataStatus("2");
        }

        tQualityFileItem.setUpdateBy(bizRectifyReviewDTO.getUserName());
        tQualityFileItem.setUpdateTime(new Date());
        tQualityFileItem.setCanDel("2");

        tQualityFileItemService.updateTQualityFileItem(tQualityFileItem);

        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 保存复查整改数据
        rectifyReview.setOperatorer(loginUser.getUsername());
        rectifyReview.setOperatorTime(DateUtils.getNowDate());
        rectifyReview.setCreateBy(loginUser.getUsername());
        rectifyReview.setCreateTime(DateUtils.getNowDate());
        bizRectifyReviewMapper.insertBizRectifyReview(rectifyReview);

        // 保存附件
        bizSafeAttachService.selectBizSafeAttachByNames(bizRectifyReviewDTO.getFileName(), rectifyReview.getId());

        return true;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addRectifyReview(List<BizRectifyReviewDTO> listBizRectifyReviews) {
        if (listBizRectifyReviews.size() > 0)
        {
            // 复查整改数据从dto复制到实体类
            BizRectifyReview rectifyReview = new BizRectifyReview();
            BeanUtil.copyProperties(listBizRectifyReviews.get(0), rectifyReview);
            // 主键id，使用雪花算法获取
            rectifyReview.setId(IdUtil.getSnowflakeNextId());


            // 查询项目自检-检查记录
            TQualityFileItem tQualityFileItem = tQualityFileItemService.selectTQualityFileItemById(
                    listBizRectifyReviews.get(0).getRecordId());

            //去掉重复和空字符串的分包单位
            Set<String> subpackageUnitAll = new HashSet<>();

            if (ObjectUtil.isNotEmpty(tQualityFileItem.getSubpackageUnit())) {
                subpackageUnitAll.addAll(Arrays.stream(tQualityFileItem.getSubpackageUnit().split(","))
                        .filter(StrUtil::isNotEmpty).collect(Collectors.toSet()));
            }

            for (BizRectifyReviewDTO bizRectifyReviewDTO : listBizRectifyReviews)
            {
                if (StrUtil.isNotEmpty(SecurityUtils.getUsername())) {
                    bizRectifyReviewDTO.setUserName(SecurityUtils.getUsername());
                }

                String subpackageUnit = bizRectifyReviewDTO.getSubpackageUnitIds();
                SysUser sysUser = sysUserMapper.selectUserByUserName(bizRectifyReviewDTO.getUserName());
                SysDept sysDept = sysDeptMapper.selectDeptById(sysUser.getDeptId());
                //查询登陆人所在部门
                if (subpackageUnit == null || subpackageUnit.isEmpty()) {

                    bizSafeFineMapper.insertBizSafeFine(BizSafeFine.builder()
                            .safeNumber(bizSafeBillnoService.getSafeNumber(1L))
                            .fineUnit(sysDept.getDeptName())
                            .fineUser(subpackageUnit)
                            .fineExplain(bizRectifyReviewDTO.getFineExplain())
                            .fineAttachment(bizRectifyReviewDTO.getOperatorPhoto())
                            .operatorExplain(bizRectifyReviewDTO.getOperatorExplain())
                            .fineSource("1")
                            .fineMoney(bizRectifyReviewDTO.getFineMoney())
                            .projectId(bizRectifyReviewDTO.getProjectId())
                            .recordId(bizRectifyReviewDTO.getRecordId())
                            .fineButton("2")
                            .createBy(bizRectifyReviewDTO.getUserName())
                            .createTime(new Date())
                            .build());

                }
                else
                {
                    bizSafeFineMapper.insertBizSafeFine(BizSafeFine.builder()
                            .safeNumber(bizSafeBillnoService.getSafeNumber(1L))
                            .fineUnit(sysDept.getDeptName())
                            .fineUser(subpackageUnit)
                            .fineExplain(bizRectifyReviewDTO.getFineExplain())
                            .fineAttachment(bizRectifyReviewDTO.getOperatorPhoto())
                            .operatorExplain(bizRectifyReviewDTO.getOperatorExplain())
                            .fineSource("1")
                            .fineMoney(bizRectifyReviewDTO.getFineMoney())
                            .projectId(bizRectifyReviewDTO.getProjectId())
                            .recordId(bizRectifyReviewDTO.getRecordId())
                            .fineButton("1")
                            .createBy(bizRectifyReviewDTO.getUserName())
                            .createTime(new Date())
                            .build());
                }

                // 保存附件
                //bizSafeAttachService.selectBizSafeAttachByNames(bizRectifyReviewDTO.getFileName(), rectifyReview.getId());

                if (ObjectUtil.isNotEmpty(listBizRectifyReviews.get(0).getSubpackageUnitIds())) {
                    subpackageUnitAll.addAll(Arrays.stream(listBizRectifyReviews.get(0).getSubpackageUnitIds().split(","))
                            .filter(StrUtil::isNotEmpty).collect(Collectors.toSet()));
                }
            }

            tQualityFileItem.setSubpackageUnit(StrUtil.join(",", subpackageUnitAll));

            rectifyReview.setOperatorType("1");
            if (rectifyReview.getOperatorStatus().equals("1"))
            {
                tQualityFileItem.setCheckTime(new Date());
                tQualityFileItem.setDataStatus("1");
            }

            LoginUser loginUser = SecurityUtils.getLoginUser();
            tQualityFileItem.setUpdateBy(loginUser.getUsername());
            tQualityFileItem.setUpdateTime(new Date());
            tQualityFileItem.setCanDel("2");

            tQualityFileItemService.updateTQualityFileItem(tQualityFileItem);

            // 保存复查整改数据
            rectifyReview.setOperatorer(loginUser.getUsername());
            rectifyReview.setOperatorTime(DateUtils.getNowDate());
            rectifyReview.setCreateBy(loginUser.getUsername());
            rectifyReview.setCreateTime(DateUtils.getNowDate());
            bizRectifyReviewMapper.insertBizRectifyReview(rectifyReview);

            // 保存附件
            //bizSafeAttachService.selectBizSafeAttachByNames(bizRectifyReviewDTO.getFileName(), rectifyReview.getId());
        }
        return true;
    }
}
